﻿using LogLib;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ComLib.ComFun
{
    public class Area
    {
        public string Province = "山东省";

        public Dictionary<string, string> CityCodes = new Dictionary<string, string>();

        public Area(string province)
        {
            Province = province;
        }

        public Area(string province, Dictionary<string, string> cities)
        {
            Province = province;
            CityCodes = cities;
        }

        public string this[string key]
        {
            get 
            {
                if (CityCodes == null)
                {
                    return null;
                }
                if (CityCodes.ContainsKey(key))
                {
                    return CityCodes[key];
                }
                else
                {
                    return null;
                }
            }
            set 
            {
                if (CityCodes == null)
                {
                    return;
                }
                if (CityCodes.ContainsKey(key))
                {
                    CityCodes[key] = value;
                }
                else
                {
                    CityCodes.Add(key, value);
                }
            }
        }

        public void AddCity(string city, string code)
        {
            if (!CityCodes.ContainsKey(city))
            {
                CityCodes.Add(city, code);
            }
        }
    }

    public class AreasConfig
    {       
        private string _xmlFilePath = "CityCode.xml";
        public string ConfigPath
        {
            get 
            {
                return _xmlFilePath;
            }
        }

        public AreasConfig()
        {
            if (!File.Exists(_xmlFilePath))
            {
                CreatXmlConfig(_xmlFilePath);
            }
        }

        public AreasConfig(string path)
        {
            _xmlFilePath = path;
            if (!File.Exists(_xmlFilePath))
            {
                CreatXmlConfig(_xmlFilePath);
            }
        }

        public static bool CreatXmlConfig(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmlDoc.AppendChild(xmlDec);
                XmlElement root = xmlDoc.CreateElement("Country");
                xmlDoc.AppendChild(root);
                xmlDoc.Save(path);
            }
            catch (System.Exception ex)
            {
                Log.WriteAsync(ex.ToString());
                return false;
            }
            return true;
        }

        public bool AddArea(Area citys)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(_xmlFilePath);
                XmlElement rows = xmlDoc["Country"];
                XmlElement row = xmlDoc.CreateElement("Province");
                row.SetAttribute("name", citys.Province);
                for (int j = 0; j < citys.CityCodes.Count(); j++)
                {
                    KeyValuePair<string, string> pair = citys.CityCodes.ElementAt(j);
                    XmlElement colElem = xmlDoc.CreateElement("City");
                    colElem.SetAttribute("name", pair.Key);
                    colElem.SetAttribute("code", pair.Value);
                    row.AppendChild(colElem);
                }
                rows.AppendChild(row);
                xmlDoc.Save(_xmlFilePath);
                return true;
            }
            catch (System.Exception ex)
            {
                Log.WriteAsync(ex.ToString());
                return false;
            }           
        }

        public string GetCode(string province, string city)
        {
            XDocument xmlDoc = XDocument.Load(_xmlFilePath);
            XElement root = xmlDoc.Element("Country");
            IEnumerable<XElement> elist = from e in root.Elements("Province")
                                          where province.Equals((e.Attribute("name").Value))
                                          select e;

            int count = elist.Count();
            if (count == 1)
            {
                XElement elemProvince = elist.First();
                IEnumerable<XElement> eCitys = from e in elemProvince.Elements("City")
                                               where city.Equals((e.Attribute("name").Value))
                                               select e;
                count = eCitys.Count();
                if (count == 1)
                {
                    XElement elem = eCitys.First();
                    return elem.Attribute("code").Value;
                }
                else
                {
                    Log.WriteAsync(string.Format("没有找到{0}{1}的区域代码", province, city));
                    return null;
                }
            }
            else
            {
                Log.WriteAsync(string.Format("没有找到{0}{1}的区域代码", province, city));
                return null;
            }          
        }

        public bool LoadAllAreas(ref List<Area> listAreas)
        {
            listAreas.Clear();
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(_xmlFilePath);
                XmlElement rows = xmlDoc["Country"];
                XmlNodeList rowList = rows.ChildNodes;
                for (int j = 0; j < rowList.Count; j++)
                {
                    XmlElement column = (XmlElement)rowList[j];
                    string name = column.Attributes["name"].Value;
                    Area area = new Area(name);
                    XmlNodeList panelList = column.ChildNodes;
                    for (int i = 0; i < panelList.Count; i++)
                    {
                        XmlElement node = (XmlElement)panelList[i];
                        string city = node.Attributes["name"].Value;
                        string code = node.Attributes["code"].Value;
                        area.AddCity(city, code);
                    }
                    listAreas.Add(area);
                }
                return true;
            }
            catch (System.Exception ex)
            {
                Log.WriteException(ex.ToString());
                return false;
            }      
        }
    }
}
